package com.symaster.backups.repository.data2.impl;

import com.symaster.backups.repository.data2.FileSystemMonitorBackupData2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yinmiao
 * @version 2024/2/22
 */
@Component
public class FileSystemMonitorBackupData2Impl implements FileSystemMonitorBackupData2 {

    private final EntityManager entityManager;

    @Autowired
    public FileSystemMonitorBackupData2Impl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List<String> findFileGroup(Integer fileSystemMonitorId, Integer patent) {
        String sql = "select distinct path_name from bk_file_system_monitor_backup_item where file_system_monitor_id = ?1 and patent = ?2 and path_type = 1";

        Query nativeQuery = entityManager.createNativeQuery(sql);
        nativeQuery.setParameter(1, fileSystemMonitorId);
        nativeQuery.setParameter(2, patent);

        List<?> resultList = nativeQuery.getResultList();
        return resultList.stream().map(e -> (String) e).collect(Collectors.toList());
    }

    @Override
    public List<String> findFileGroup(Integer fileSystemMonitorId) {
        String sql = "select distinct path_name from bk_file_system_monitor_backup_item where file_system_monitor_id = ?1 and patent is null and path_type = 1";

        Query nativeQuery = entityManager.createNativeQuery(sql);
        nativeQuery.setParameter(1, fileSystemMonitorId);

        List<?> resultList = nativeQuery.getResultList();
        return resultList.stream().map(e -> (String) e).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void updateMonitor(Integer id, boolean monitor) {
        String sql = "update bk_file_system_monitor set monitor = ?2, updated_time = ?3 where id = ?1";

        Query nativeQuery = entityManager.createNativeQuery(sql);
        nativeQuery.setParameter(1, id);
        nativeQuery.setParameter(2, monitor);
        nativeQuery.setParameter(3, new Date());
        nativeQuery.executeUpdate();
    }
}
